// @title						Demo API
// @version					1.0.0
// @description				This is a demo API for testing purposes.
// @host						localhost:8080
// @BasePath					/
// @securityDefinitions.apikey	BearerAuth
// @in							header
// @name						Authorization
package main

import (
	"demo/internal/config"
	"demo/internal/handler"
	"demo/internal/middleware"
	"demo/internal/model"
	"demo/internal/repository"
	"demo/internal/service"
	"log"

	"github.com/gin-gonic/gin"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"

	swaggerFiles "github.com/swaggo/files"
	ginSwagger "github.com/swaggo/gin-swagger"

	_ "demo/docs" // docs is generated by Swag CLI, you have to import it.
)

func main() {
	cfg := config.Load()

	db, err := gorm.Open(mysql.Open(cfg.DB.DSN), &gorm.Config{})
	if err != nil {
		log.Fatalf("Failed to connect to database: %v", err)
	}
	db.AutoMigrate(&model.User{})

	// 初始化依赖
	userRepo := repository.NewUserRepo(db)
	userService := service.NewUserService(userRepo)

	// 初始化 handlers
	accountHandler := handler.NewAccountHandler(userService, cfg)
	userHandler := handler.NewUserHandler(userService)

	r := gin.Default()

	// 添加 Swagger UI 路由
	r.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))

	// 公开路由
	r.POST("/signup", accountHandler.SignUp)
	r.POST("/login", accountHandler.Login)

	// 受保护的路由
	protected := r.Group("/api")
	protected.Use(middleware.JWT(cfg.JWT.Secret))
	{
		// 用户相关路由
		protected.GET("/profile", accountHandler.Profile)
		protected.GET("/users", userHandler.ListUsers)
	}

	r.Run(":8080")
}
